<!--
 * @Descripttion :
 * @Author       : RAN
 * @Date         : 2021-07-14 09:49:40
 * @LastEditors  : RAN
 * @LastEditTime : 2021-07-15 17:57:16
-->
<template>
  <tsl-chart class="chart" ref="myEcharts" :option="option" @click="handleClick" />
</template>

<script>
import { Chart } from "tsl-vue";
import { use, graphic } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { LineChart } from "echarts/charts";
import dayjs from "dayjs";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from "echarts/components";

use([TitleComponent, TooltipComponent, GridComponent, LineChart, CanvasRenderer, LegendComponent]);

export default {
  name: "myLine",
  components: {
    TslChart: Chart
  },
  data() {
    return {
      option: {},
      timer: null
    };
  },
  mounted() {
    const that = this;
    this.option = {
      grid: {
        right: 55,
        left: 115,
        top: 86,
        bottom: 40
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          lineStyle: {
            opacity: 0
          },
          z: -1,
          // 坐标轴指示器，坐标轴触发有效
          type: "line" // 默认为直线，可选为：'line' | 'shadow'
        },
        // formatter:
        //   "{a0}&nbsp;&nbsp; {c0}<br />{a1}&nbsp; {c1}<br />{a2}&nbsp; {c2}<br />{a3}&nbsp; {c3}<br />{a4}&nbsp; {c4}",
        formatter: (arr) => {
          let result = "";
          arr.forEach((p) => {
            result += `${p.seriesName}${p.seriesIndex === 0 ? "&nbsp;" : ""}  ${this.formatNum(
              p.value
            )}<br />`;
          });
          return result;
        },
        triggerOn: "none",
        borderColor: "#44C7F2",
        // position: "left",
        position: ["70%", "30%"],
        borderWidth: 2,
        padding: [20, 25, 30, 25],
        backgroundColor: "rgba(27, 38, 70, 0.9)",
        textStyle: {
          fontSize: 25,
          color: "rgba(255, 255, 255, 1)"
        }
      },
      legend: {
        show: true,
        icon: "rect",
        top: 36,
        itemGap: 35,
        itemWidth: 30,
        itemHeight: 6,
        textStyle: {
          color: "rgba(255, 255, 255, 0.7)",
          fontSize: "1.56vh"
        }
      },
      animationEasing: "elasticOut",
      xAxis: [
        {
          type: "category",
          offset: 10,
          boundaryGap: false,
          data: this.genLastTenData(5),

          axisLabel: {
            color: "rgba(153, 153, 153, 1)",
            fontSize: "1.62vh",
            fontWeight: 400
            // rotate: 40
          },
          axisLine: {
            lineStyle: {
              color: "rgba(191, 191, 191, 1)"
            }
          },
          splitLine: {
            lineStyle: {
              color: "rgba(191, 191, 191, 1)"
            }
          }
        }
      ],
      yAxis: [
        {
          type: "value",
          offset: 30,
          min: 0,
          axisLabel: {
            color: "rgba(153, 153, 153, 1)",
            fontSize: "1.62vh",
            fontWeight: 400,
            formatter: function (value) {
              if (value == 0) {
                return `${value}次`;
              }
              return value;
            }
          },
          axisLine: {
            lineStyle: {
              color: "rgba(191, 191, 191, 1)"
            }
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: "rgba(191, 191, 191, 0.3)"
            }
          }
        }
      ],
      series: [
        {
          showSymbol: false,
          type: "line",
          name: "IoT服务",
          data: this.randomData("iot", 5),
          smooth: 0.5,
          lineStyle: {
            width: 3,
            color: "rgba(253,125,96,1)"
          },
          animationEasing: "linear",
          itemStyle: {
            color: new graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset: 0,
                color: "rgba(253,125,96, 0)" //todo
              },
              {
                offset: 1,
                color: "rgba(253,125,96,0.37)"
              }
            ])
          },
          areaStyle: {}
        },
        {
          showSymbol: false,
          type: "line",
          name: "算法服务",
          data: this.randomData("suanf", 5),
          smooth: 0.5,
          lineStyle: {
            width: 3,
            color: "rgba(37,215,253,1)"
          },
          animationEasing: "linear",
          itemStyle: {
            color: new graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset: 0,
                color: "rgba(37,215,253,0)" //todo
              },
              {
                offset: 1,
                color: "rgba(37,215,253,0.37)"
              }
            ])
          },
          areaStyle: {}
        },
        {
          showSymbol: false,
          type: "line",
          name: "数据服务",
          data: this.randomData("shuj", 5),
          smooth: 0.5,
          lineStyle: {
            width: 3,
            color: "rgba(151 ,98 ,247,1)"
          },
          animationEasing: "linear",
          itemStyle: {
            color: new graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset: 0,
                color: "rgba(151 ,98 ,247, 0)" //todo
              },
              {
                offset: 1,
                color: "rgba(151 ,98 ,247,0.37)"
              }
            ])
          },
          areaStyle: {}
        },
        {
          showSymbol: false,
          type: "line",
          name: "孪生服务",
          data: this.randomData("luans", 5),
          smooth: 0.5,
          lineStyle: {
            width: 3,
            color: "rgba(43,248,246,1)"
          },
          animationEasing: "linear",
          itemStyle: {
            color: new graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset: 0,
                color: "rgba(43,248,246, 0)" //todo
              },
              {
                offset: 1,
                color: "rgba(43,248,246,0.37)"
              }
            ])
          },
          areaStyle: {}
        },
        {
          showSymbol: false,
          type: "line",
          name: "通用服务",
          data: this.randomData("tongy", 5),
          smooth: 0.5,
          lineStyle: {
            width: 3,
            color: "rgba(254,206,65,1)"
          },
          animationEasing: "linear",
          itemStyle: {
            color: new graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset: 0,
                color: "rgba(254,206,65,0)" //todo
              },
              {
                offset: 1,
                color: "rgba(254,206,65,0.37)"
              }
            ])
          },
          areaStyle: {}
        }
      ]
    };
    // this.setTimer();
    this.setTimerNew();
  },
  beforeDestroy() {
    this.timer && clearInterval(this.timer);
  },
  methods: {
    // 生成以当前时间为基础的 最近num个x轴数据
    genLastTenData(num) {
      var result = [];
      var current = dayjs();
      for (let i = 0; i < num; i++) {
        result.unshift(current.subtract(i, "s").format("mm'ss''"));
      }
      return result;
    },
    randomData(key, num) {
      let result = [];
      for (let index = 0; index < num; index++) {
        result.push(this.randomDataByType(key));
      }
      return result;
    },
    randomDataByType(key) {
      let num = 0;
      switch (key) {
        case "iot":
          num = this.randomNumber(2000, 4000);
          break;
        case "suanf":
          num = this.randomNumber(2500, 4500);
          break;
        case "shuj":
          num = this.randomNumber(2500, 4500);
          break;
        case "luans":
          num = this.randomNumber(4000, 5000);
          break;
        case "tongy":
          num = this.randomNumber(3000, 4000);
          break;
        default:
          num = this.randomNumber(2000, 4000);
          break;
      }
      return num;
    },
    compileData() {},
    setTimer() {
      const option = JSON.parse(JSON.stringify(this.option));
      this.timer = setInterval(() => {
        var axisData = this.option.xAxis[0].data[this.option.xAxis[0].data.length - 1];
        var data0 = option.series[0].data;
        var data1 = option.series[1].data;
        var data2 = option.series[2].data;
        var data3 = option.series[3].data;
        var data4 = option.series[4].data;
        data0.shift();
        data0.push(this.randomNumber(13000, 15000));
        data1.shift();
        data1.push(this.randomNumber(8000, 12000));
        data2.shift();
        data2.push(this.randomNumber(7000, 13000));
        data3.shift();
        data3.push(this.randomNumber(2000, 5000));
        data4.shift();
        data4.push(this.randomNumber(15000, 20000));

        option.xAxis[0].data.shift();
        option.xAxis[0].data.push(dayjs().format("mm分ss秒"));
        this.option = option;
        this.$refs.myEcharts.dispatchAction({
          type: "hideTip"
        });
        this.$refs.myEcharts.dispatchAction({
          type: "showTip",
          seriesIndex: 0,
          dataIndex: this.option.xAxis[0].data.length - 1
        });
      }, 1000);
    },
    setTimerNew() {
      const option = JSON.parse(JSON.stringify(this.option));
      this.timer = setInterval(() => {
        option.series[0].data = this.randomData("iot", 5);
        option.series[1].data = this.randomData("suanf", 5);
        option.series[2].data = this.randomData("shuj", 5);
        option.series[3].data = this.randomData("luans", 5);
        option.series[4].data = this.randomData("tongy", 5);

        option.xAxis[0].data = this.genLastTenData(5);
        this.option = option;
        this.$refs.myEcharts.dispatchAction({
          type: "hideTip"
        });
        this.$refs.myEcharts.dispatchAction({
          type: "showTip",
          seriesIndex: 0,
          dataIndex: this.option.xAxis[0].data.length - 1
        });
      }, 5000);
    },
    // 指定范围随机数
    randomNumber(min, max) {
      return parseInt(Math.random() * (max - min)) + min;
    },
    handleClick(p) {
      console.log(p);
    },
    /**
     * @description: 数字加千分位
     * @param {*} number
     * @return {*}
     */
    formatNum(number) {
      const num = String(number);
      const reg = /\d{1,3}(?=(\d{3})+$)/g;
      return num.replace(/^(-?)(\d+)((\.\d+)?)$/, function (match, s1, s2, s3) {
        return s1 + s2.replace(reg, "$&,") + s3;
      });
    }
  }
};
</script>

<style scoped>
.chart {
  width: 100%;
}
</style>
